import pandas as pd
from datetime import datetime
import backtrader as bt
import matplotlib.pyplot as plt
from AvgStrage import SMAStrategy as avgStrage

import os

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置画图时中文显示
plt.rcParams["axes.unicode_minus"] = False  # 设置画图时的负号显示


cerebro = bt.Cerebro()  # 构建大脑

# 1.数据加载
def get_datas(code='600519', starttime='2017-01-01', endtime='2020-01-01'):

    all_latest_kline_data = {}

    folder_path = "tem"
    csv_files = [f for f in os.listdir(folder_path) if f.endswith('.csv')]
    for csv_file in csv_files:
        data_path = os.path.join(folder_path, csv_file)
        df = pd.read_csv(data_path)
        df.columns = ['symbol', 'datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest',
                      'turnover', 'settle', 'pre_settle', 'variety', 'local_symbol']
        df['datetime'] = pd.to_datetime(df['datetime'], format='%Y%m%d')
        code_str = df['symbol'][0]
        min_datetime = df['datetime'].min()
        max_datetime = df['datetime'].max()
        print(min_datetime, max_datetime)
        df.index = pd.to_datetime(df.datetime)
        # df['openinterest'] = 0
        # 对df的数据列进行一个整合
        df = df[['open', 'high', 'low', 'close', 'volume', 'openinterest', 'datetime']]
        df.dropna(axis=0, how='any')
        all_latest_kline_data[code_str] = df

    return all_latest_kline_data



stock_df_s = get_datas()

for futures_code, kline_data in stock_df_s.items():
    fromdate = kline_data['datetime'].min()
    todata = kline_data['datetime'].max()
    # 加载并读取数据源 dataname(数据来源) fromdate（date格式） todate
    data = bt.feeds.PandasData(dataname=kline_data, fromdate=fromdate, todate=todata)
    cerebro.adddata(data, futures_code)  # 添加数据

# 3.策略设置

cerebro.addstrategy(avgStrage)  # 添加策略

# 设置初始金额
cash = 100000
cerebro.broker.setcash(cash)
# 设置手续费
cerebro.broker.setcommission(commission=0.0002)

cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')

# 4.运行

print('初始金额: %.2f、' % (cash))
result = cerebro.run()
print('最终金额: %.2f 回测时间' % (cerebro.broker.getvalue()))
strats = result[0]
print('Sharpe Ratio:', strats.analyzers.sharpe.get_analysis())
print('DrawDown:', strats.analyzers.drawdown.get_analysis())

# 打印交易单 AttributeError: 'Lines_LineSeries_LineIterator_DataAccessor_Strateg' object has no attribute 'trades'

for i in range(len(result)):
    strat = result[i]
    print('第%d个策略的交易单：' % (i + 1))
    for j in range(len(strat.trades)):
        trade = strat.trades[j]
        print('第%d笔交易：' % (j + 1))
        print('开仓时间：%s，开仓价格：%s，开仓类型：%s' % (trade.data._name, trade.price, trade.history[0]['status']))
        print('平仓时间：%s，平仓价格：%s，平仓类型：%s' % (trade.data._name, trade.history[-1]['price'], trade.history[-1]['status']))
        print('交易利润：%s' % (trade.history[-1]['pnl']))
        print('交易手续费：%s' % (trade.history[-1]['commission']))
        print('交易盈亏：%s' % (trade.history[-1]['pnlcomm']))

#cerebro.plot(style='candlestick', barup='red', bardown='green', fmt_x_data='%Y-%m-%d', fmt_x_ticks='%Y-%m-%d')


